<template>
    <div>
        <el-button type="primary" @click="openAddDialog">新增</el-button>
        
        <!-- 新增 Dialog -->
        <el-dialog v-model="addDialogVisible" title="新增" width="500">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="custom-form">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" clearable maxlength="30" />
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="form.type">
                        <el-radio :label="'all'">全检</el-radio>
                        <el-radio :label="'sample'">抽检</el-radio>
                    </el-radio-group>
                </el-form-item>
                <template v-if="form.type === 'sample'">
                    <el-form-item label="抽检方式" prop="sampleType">
                        <el-radio-group v-model="form.sampleType">
                            <el-radio :label="'percent'">百分比</el-radio>
                            <el-radio :label="'interval'">间隔</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item
                        label="值"
                        prop="valueGroup"
                        class="value-item"
                    >
                        <template v-if="form.sampleType === 'percent'">
                            <el-input
                                v-model="form.percentValue"
                                placeholder="请输入百分比"
                                style="width: 120px;"
                                clearable
                                type="number"
                            />
                            <span class="percent-sign">%</span>
                        </template>
                        <template v-else>
                            <span>每间隔</span>
                            <el-input
                                v-model="form.intervalValue"
                                placeholder="间隔值"
                                style="width: 80px; margin: 0 6px;"
                                clearable
                                type="number"
                            />
                            <span>抽取</span>
                            <el-input
                                v-model="form.intervalCount"
                                placeholder="抽取值"
                                style="width: 80px; margin: 0 6px;"
                                clearable
                                type="number"
                            />
                        </template>
                    </el-form-item>
                </template>
                <el-form-item label="检验项目" prop="items" class="item-select">
                    <el-input v-model="selectedItemsText" placeholder="请选择数据" readonly style="width: 260px;" />
                    <el-button @click="openItemDialog" type="primary" style="margin-left: 10px;">选择</el-button>
                </el-form-item>
                <el-form-item label="描述" prop="desc">
                    <el-input v-model="form.desc" placeholder="请输入描述" type="textarea" :rows="2" maxlength="100" show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 检验项目穿梭框 Dialog -->
        <el-dialog v-model="itemDialogVisible" title="选择数据" width="600px" :close-on-click-modal="false">
            <div class="transfer-wrapper">
                <el-transfer
                    v-model="form.items"
                    :data="itemOptions"
                    filterable
                    filter-placeholder="请输入搜索内容"
                    :titles="['可选项目', '已选项目']"
                    :props="{ key: 'id', label: 'name' }"
                    class="custom-transfer"
                />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="itemDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmItems">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <div>
        <!-- 检验方案主表 -->
        <el-table
            :data="tableData"
            style="width: 100%; margin-top: 18px"
            row-key="id"
            :default-expand-all="false"
            border
        >
            <!-- 展开行 -->
            <el-table-column type="expand">
                <template #default="props">
                    <el-table :data="props.row.items" size="small" border>
                        <el-table-column prop="name" label="名称" />
                        <el-table-column prop="method" label="作业方式" />
                        <el-table-column prop="standard" label="标准值" />
                        <el-table-column prop="unit" label="单位" />
                        <el-table-column prop="upper" label="上限值" />
                        <el-table-column prop="lower" label="下限值" />
                    </el-table>
                </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="type" label="类型">
                <template #default="{ row }">
                    <el-tag :type="row.type === 'all' ? 'success' : 'info'">
                        {{ row.type === 'all' ? '全检' : '抽检' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="sampleType" label="抽检方式">
                <template #default="{ row }">
                    <el-tag v-if="row.type === 'sample'" :type="row.sampleType === 'percent' ? 'warning' : 'danger'">
                        {{ row.sampleType === 'percent' ? '百分比' : '间隔' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="value" label="值" />
            <el-table-column prop="desc" label="描述" />
            <el-table-column prop="creator" label="创建人" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column label="操作" width="180">
                <template #default="{ row, $index }">
                    <el-button type="primary" size="small" @click="openEditDialog(row, $index)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteScheme($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { ElMessage } from 'element-plus'

// 类型定义（如用TS，直接写在这里）
interface InspectionItem {
    id: string
    name: string
    method?: string
    standard?: string
    unit?: string
    upper?: string
    lower?: string
}
interface InspectionScheme {
    id: string
    name: string
    type: 'all' | 'sample'
    sampleType?: 'percent' | 'interval'
    value?: string
    items: InspectionItem[]
    desc: string
    creator: string
    createTime: string
    updateTime: string
}

//#region 新增功能
const addDialogVisible = ref(false)
const itemDialogVisible = ref(false)
const formRef = ref()

// 表单数据
const form = ref<{
    name: string
    type: 'all' | 'sample'
    sampleType: 'percent' | 'interval'
    percentValue: string
    intervalValue: string
    intervalCount: string
    items: string[]
    desc: string
}>({
    name: '',
    type: 'all',
    sampleType: 'percent',
    percentValue: '',
    intervalValue: '',
    intervalCount: '',
    items: [],
    desc: ''
})

// 校验规则
const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    sampleType: [
        { required: true, message: '请选择抽检方式', trigger: 'change' }
    ],
    valueGroup: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (form.value.type !== 'sample') return callback();
                if (form.value.sampleType === 'percent') {
                    if (!form.value.percentValue) return callback(new Error('请输入百分比'));
                    if (!/^\d+(\.\d+)?$/.test(form.value.percentValue)) return callback(new Error('请输入数字'));
                } else {
                    if (!form.value.intervalValue) return callback(new Error('请输入间隔值'));
                    if (!/^\d+(\.\d+)?$/.test(form.value.intervalValue)) return callback(new Error('请输入数字'));
                    if (!form.value.intervalCount) return callback(new Error('请输入抽取值'));
                    if (!/^\d+(\.\d+)?$/.test(form.value.intervalCount)) return callback(new Error('请输入数字'));
                }
                callback();
            },
            trigger: ['blur', 'change']
        }
    ],
    items: [{ required: true, message: '请选择检验项目', trigger: 'change' }],
    desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

// 检验项目选项（模拟数据，实际请替换为接口数据）
const itemOptions = ref<InspectionItem[]>([
    { id: '1', name: '项目A' },
    { id: '2', name: '项目B' },
    { id: '3', name: '项目C' }
])

// 选中项目的文本
const selectedItemsText = computed(() =>
    form.value.items
        .map((id: string) => itemOptions.value.find(item => item.id === id)?.name)
        .filter(Boolean)
        .join('，')
)

// 打开新增弹窗
function openAddDialog() {
    addDialogVisible.value = true
    // 重置表单
    form.value = {
        name: '',
        type: 'all',
        sampleType: 'percent',
        percentValue: '',
        intervalValue: '',
        intervalCount: '',
        items: [],
        desc: ''
    }
    editIndex.value = -1
}

// 打开检验项目穿梭框
function openItemDialog() {
    itemDialogVisible.value = true
}

// 确认选择检验项目
function confirmItems() {
    itemDialogVisible.value = false
}

//#endregion

// 方案数据
const tableData = ref<InspectionScheme[]>([
    {
        id: '1',
        name: 'TEST',
        type: 'sample',
        sampleType: 'interval',
        value: '每间隔10抽取1',
        items: [
            { id: '1', name: '高度', method: '卡尺', standard: '10.1', unit: 'cm', upper: '10.5', lower: '9.5' },
            // ...更多项目
        ],
        desc: '描述内容',
        creator: '(test)毛猫子',
        createTime: '2024-07-06 10:16:18',
        updateTime: '2025-02-02 15:19:07'
    },
    // ...更多方案
])

// 编辑相关
const editIndex = ref(-1)
function openEditDialog(row: InspectionScheme, index: number) {
    let percentValue = '';
    let intervalValue = '';
    let intervalCount = '';
    if (row.type === 'sample') {
        if (row.sampleType === 'percent' && row.value) {
            percentValue = row.value.replace('%', '');
        } else if (row.sampleType === 'interval' && row.value) {
            // 例如"每间隔5抽取1"
            const match = row.value.match(/每间隔(\d+)抽取(\d+)/);
            if (match) {
                intervalValue = match[1];
                intervalCount = match[2];
            }
        }
    }
    form.value = {
        name: row.name,
        type: row.type,
        sampleType: row.sampleType ?? 'percent',
        percentValue,
        intervalValue,
        intervalCount,
        items: row.items.map((i: InspectionItem) => i.id),
        desc: row.desc
    }
    editIndex.value = index
    addDialogVisible.value = true
}

// 删除
function deleteScheme(index: number) {
    tableData.value.splice(index, 1)
    ElMessage.success('删除成功')
}

// 新增/编辑保存
function submitForm() {
    formRef.value.validate((valid: boolean) => {
        if (valid) {
            if (editIndex.value > -1) {
                // 编辑
                let value = '';
                if (form.value.type === 'sample') {
                    if (form.value.sampleType === 'percent') {
                        value = form.value.percentValue + '%';
                    } else {
                        value = `每间隔${form.value.intervalValue}抽取${form.value.intervalCount}`;
                    }
                }
                tableData.value[editIndex.value] = {
                    ...tableData.value[editIndex.value],
                    name: form.value.name,
                    type: form.value.type as 'all' | 'sample',
                    sampleType: form.value.sampleType as 'percent' | 'interval',
                    value,
                    items: itemOptions.value.filter(i => form.value.items.includes(i.id)),
                    desc: form.value.desc,
                    updateTime: new Date().toLocaleString()
                }
                ElMessage.success('编辑成功')
            } else {
                // 新增
                let value = '';
                if (form.value.type === 'sample') {
                    if (form.value.sampleType === 'percent') {
                        value = form.value.percentValue + '%';
                    } else {
                        value = `每间隔${form.value.intervalValue}抽取${form.value.intervalCount}`;
                    }
                }
                tableData.value.push({
                    id: Date.now().toString(),
                    name: form.value.name,
                    type: form.value.type as 'all' | 'sample',
                    sampleType: form.value.sampleType as 'percent' | 'interval',
                    value,
                    items: itemOptions.value.filter(i => form.value.items.includes(i.id)),
                    desc: form.value.desc,
                    creator: '当前用户',
                    createTime: new Date().toLocaleString(),
                    updateTime: new Date().toLocaleString()
                })
                ElMessage.success('新增成功')
            }
            addDialogVisible.value = false
            editIndex.value = -1
        }
    })
}

function renderRequiredLabel(label: string) {
    return h('span', [
        h('span', { style: 'color: #F56C6C; margin-right: 4px;' }, '*'),
        label
    ])
}
</script>

<style scoped>
.custom-form .el-form-item {
    margin: 10px 20px 20px 10px;
}
.value-item {
    display: flex;
    align-items: center;
}
.percent-sign {
    margin-left: 8px;
    color: #888;
    font-size: 15px;
}
.item-select {
    display: flex;
    align-items: center;
}
.dialog-footer {
    text-align: center;
    padding-bottom: 10px;
}
.transfer-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 320px;
}
.custom-transfer {
    width: 100%;
}
.el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0;
}
</style>